import 'dart:convert';
import 'dart:io';

import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart';
import '../../../app_files.dart';

import 'action.dart';
import 'state.dart';

Widget buildView(EngineerIndoorReasonViewState state, Dispatch dispatch,
    ViewService viewService) {
  Widget _orderStatusWidget() {
    List<String> titles = ['已解决', '未解决'];
    Widget _button(int index, String text) {
      int t = state.isSolve == null
          ? -1
          : state.isSolve
              ? 0
              : 1;
      return InkWell(
        child: Container(
          width: 80,
          height: 30,
          margin: EdgeInsets.only(right: 20, bottom: 20),
          decoration: BoxDecoration(
            color: t == index ? Color(0xffE6EEFF) : Color(0xfff5f5f5),
            borderRadius: BorderRadius.all(Radius.circular(4)),
          ),
          child: Align(
            child: Text(
              text,
              style: t == index
                  ? TextThemeConfig.Font13WithColorblue
                  : TextThemeConfig.Font13WithColor66,
            ),
          ),
        ),
        onTap: () {
          state.isSolve = index == 0;
          dispatch(EngineerIndoorReasonViewActionCreator.onAction());
        },
      );
    }

    List<Widget> items = [];
    for (int i = 0; i < 2; ++i) {
      items.add(_button(i, titles[i]));
    }

    return Container(
      padding: EdgeInsets.only(left: 15, right: 15),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
              bottom: BorderSide(color: ThemeConfig.separeColor, width: 10))),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            height: 44,
            child: Align(
              alignment: Alignment.centerLeft,
              child: Text(
                '报装结果',
                style: TextThemeConfig.Font16WithColorBold22,
              ),
            ),
            margin: EdgeInsets.only(bottom: 4),
          ),
          Container(
            child: Row(
              children: items,
            ),
          ),
        ],
      ),
    );
  }

  Widget _fixItemContent() {
    return MyInkWellWidget(
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.only(left: 15, right: 15, bottom: 15),
            decoration: BoxDecoration(
                color: Colors.white,
                border: Border(
                    bottom:
                        BorderSide(color: ThemeConfig.separeColor, width: 10))),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  height: 44,
                  child: Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      '情况说明',
                      style: TextThemeConfig.Font16WithColorBold22,
                    ),
                  ),
                  margin: EdgeInsets.only(bottom: 4),
                ),
                InkWell(
                  child: Container(
                    child: Row(
                      children: [
                        Image.asset(state.content == '电话沟通解决' && !state.isOther
                            ? 'images/icon_select.png'
                            : 'images/icon_normal.png'),
                        Padding(padding: EdgeInsets.only(left: 15)),
                        Text(
                          '电话沟通解决',
                          style: TextThemeConfig.Font14WithColor22,
                        ),
                      ],
                    ),
                  ),
                  onTap: () {
                    state.content = '电话沟通解决';
                    state.isOther = false;
                    dispatch(EngineerIndoorReasonViewActionCreator.onAction());
                  },
                ),
                Padding(padding: EdgeInsets.only(top: 20)),
                InkWell(
                  child: Container(
                    child: Row(
                      children: [
                        Image.asset(
                            state.content == '电话打不通，无法联系客户' && !state.isOther
                                ? 'images/icon_select.png'
                                : 'images/icon_normal.png'),
                        Padding(padding: EdgeInsets.only(left: 15)),
                        Text(
                          '电话打不通，无法联系客户',
                          style: TextThemeConfig.Font14WithColor22,
                        ),
                      ],
                    ),
                  ),
                  onTap: () {
                    state.content = '电话打不通，无法联系客户';
                    state.isOther = false;
                    dispatch(EngineerIndoorReasonViewActionCreator.onAction());
                  },
                ),
                Padding(padding: EdgeInsets.only(top: 20)),
                InkWell(
                  child: Container(
                    child: Row(
                      children: [
                        Image.asset(state.isOther == true
                            ? 'images/icon_select.png'
                            : 'images/icon_normal.png'),
                        Padding(padding: EdgeInsets.only(left: 15)),
                        Text(
                          '其他情况',
                          style: TextThemeConfig.Font14WithColor22,
                        ),
                      ],
                    ),
                  ),
                  onTap: () {
                    state.isOther = true;
                    dispatch(EngineerIndoorReasonViewActionCreator.onAction());
                  },
                ),
                Container(
                  padding: EdgeInsets.only(top: 4),
                  height: 100,
                  child: TextField(
                    minLines: 1,
                    maxLines: 10,
                    style: TextThemeConfig.Font13WithColor22,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: "请在此处填写备注信息...",
                      hintStyle: TextThemeConfig.Font13WithColor99,
                      contentPadding: EdgeInsets.only(),
                    ),
                    controller: state.textEditingController,
                  ),
                ),
                // Offstage(
                //   child: Container(
                //     padding: EdgeInsets.only(top: 4),
                //     height: 100,
                //     child: TextField(
                //       minLines: 1,
                //       maxLines: 10,
                //       style: TextThemeConfig.Font13WithColor22,
                //       decoration: InputDecoration(
                //         border: InputBorder.none,
                //         hintText: "请在此处描述问题...",
                //         hintStyle: TextThemeConfig.Font13WithColor99,
                //         contentPadding: EdgeInsets.only(),
                //       ),
                //       onChanged: (String str) {
                //         state.content = str;
                //       },
                //     ),
                //   ),
                //   offstage: !state.isOther,
                // )
              ],
            ),
          ),
          _orderStatusWidget(),
          Container(
            margin: EdgeInsets.only(left: 15, right: 15, top: 30, bottom: 12),
            height: 45,
            decoration: BoxDecoration(
              color: ThemeConfig.mainColor,
              borderRadius: BorderRadius.all(Radius.circular(4)),
            ),
            child: InkWell(
              child: Center(
                child: Text(
                  '提交',
                  style: TextThemeConfig.Font16WithWhite,
                ),
              ),
              onTap: () async {
                if (state.isSolve == null) {
                  CommonUtils.showErrorInfo(viewService.context, '请选择报装结果');
                  return;
                }

                CommonUtils.showWaitLoading(viewService.context);
                Map info = {};
                List<String> items = [state.isOther ? '其他情况' : state.content];
                if (state.textEditingController.text.isNotEmpty) {
                  items.add(state.textEditingController.text);
                }
                info['RepairContent'] = items.join(':');
                ResultData res = await CommonNetWork.engineerOrderFix(
                  state.model.itemID,
                  status: 5,
                  content: jsonEncode(info),
                  isSolve: state.isSolve,
                );
                Navigator.pop(viewService.context);
                if (res.success) {
                  bus.emit('refreshList');
                  await CommonUtils.showAlertView(viewService.context, '提交成功');
                  Navigator.popUntil(
                      viewService.context, ModalRoute.withName('/'));
                } else {
                  CommonUtils.showErrorInfo(viewService.context, res.desc);
                }
              },
            ),
          ),
        ],
      ),
      onTap: () => CommonUtils.closeKey(viewService.context),
    );
  }


  Widget _orderPhotoWidget() {
    return Container(
      padding: EdgeInsets.only(left: 15, right: 15),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
              bottom: BorderSide(color: ThemeConfig.separeColor, width: 10))),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            height: 44,
            child: Align(
              alignment: Alignment.centerLeft,
              child: Text(
                '拍照留存',
                style: TextThemeConfig.Font16WithColorBold22,
              ),
            ),
            margin: EdgeInsets.only(bottom: 4),
          ),
          Container(
            margin: EdgeInsets.only(bottom: 12),
            height: 90,
            child: ListView.builder(
              itemBuilder: (BuildContext context, int index) {
                if (index == state.orderPhoto.length) {
                  return InkWell(
                    child: Container(
                      margin: EdgeInsets.only(right: 12),
                      width: 90,
                      height: 90,
                      color: Color(0xffF5F5F5),
                      child: Align(
                        child: Image.asset('images/icon_camera.png'),
                      ),
                    ),
                    onTap: () => dispatch(
                        EngineerIndoorReasonViewActionCreator.onTapAddPic()),
                  );
                } else {
                  var file = state.orderPhoto[index];
                  return InkWell(
                    child: Container(
                      margin: EdgeInsets.only(right: 12),
                      child: file is File
                          ? Image(
                        image: FileImageEx(file),
                        width: 90,
                        height: 90,
                        fit: BoxFit.fill,
                      )
                          : CustomImage(
                        file,
                        fit: BoxFit.fill,
                        width: 90,
                        height: 90,
                      ),
                    ),
                    onTap: () => dispatch(
                        EngineerIndoorReasonViewActionCreator.onTapPic(file)),
                  );
                }
              },
              itemCount: state.orderPhoto.length + 1,
              scrollDirection: Axis.horizontal,
              itemExtent: 112,
              padding: EdgeInsets.only(),
            ),
          )
        ],
      ),
    );

  }

  Widget _engineerGasContent() {
    return MyInkWellWidget(
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.only(left: 15, right: 15, bottom: 15),
            decoration: BoxDecoration(
                color: Colors.white,
                border: Border(
                    bottom:
                        BorderSide(color: ThemeConfig.separeColor, width: 10))),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  height: 44,
                  child: Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      '情况说明',
                      style: TextThemeConfig.Font16WithColorBold22,
                    ),
                  ),
                  margin: EdgeInsets.only(bottom: 4),
                ),
                InkWell(
                  child: Container(
                    child: Row(
                      children: [
                        Image.asset(state.content == '未符合安装标准' && !state.isOther
                            ? 'images/icon_select.png'
                            : 'images/icon_normal.png'),
                        Padding(padding: EdgeInsets.only(left: 15)),
                        Text(
                          '未符合安装标准',
                          style: TextThemeConfig.Font14WithColor22,
                        ),
                      ],
                    ),
                  ),
                  onTap: () {
                    state.content = '未符合安装标准';
                    state.isOther = false;
                    dispatch(EngineerIndoorReasonViewActionCreator.onAction());
                  },
                ),
                Padding(padding: EdgeInsets.only(top: 20)),
                InkWell(
                  child: Container(
                    child: Row(
                      children: [
                        Image.asset(
                            state.content == '电话打不通，无法联系客户' && !state.isOther
                                ? 'images/icon_select.png'
                                : 'images/icon_normal.png'),
                        Padding(padding: EdgeInsets.only(left: 15)),
                        Text(
                          '电话打不通，无法联系客户',
                          style: TextThemeConfig.Font14WithColor22,
                        ),
                      ],
                    ),
                  ),
                  onTap: () {
                    state.content = '电话打不通，无法联系客户';
                    state.isOther = false;
                    dispatch(EngineerIndoorReasonViewActionCreator.onAction());
                  },
                ),
                Padding(padding: EdgeInsets.only(top: 20)),
                InkWell(
                  child: Container(
                    child: Row(
                      children: [
                        Image.asset(state.isOther == true
                            ? 'images/icon_select.png'
                            : 'images/icon_normal.png'),
                        Padding(padding: EdgeInsets.only(left: 15)),
                        Text(
                          '其他情况',
                          style: TextThemeConfig.Font14WithColor22,
                        ),
                      ],
                    ),
                  ),
                  onTap: () {
                    state.isOther = true;
                    dispatch(EngineerIndoorReasonViewActionCreator.onAction());
                  },
                ),
                Container(
                  padding: EdgeInsets.only(top: 4),
                  height: 100,
                  child: TextField(
                    minLines: 1,
                    maxLines: 10,
                    style: TextThemeConfig.Font13WithColor22,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: "请在此处填写备注信息...",
                      hintStyle: TextThemeConfig.Font13WithColor99,
                      contentPadding: EdgeInsets.only(),
                    ),
                    controller: state.textEditingController,
                  ),
                ),
              ],
            ),
          ),
          _orderStatusWidget(),
          Container(
            margin: EdgeInsets.only(left: 15, right: 15, top: 30, bottom: 12),
            height: 45,
            decoration: BoxDecoration(
              color: ThemeConfig.mainColor,
              borderRadius: BorderRadius.all(Radius.circular(4)),
            ),
            child: InkWell(
              child: Center(
                child: Text(
                  '提交',
                  style: TextThemeConfig.Font16WithWhite,
                ),
              ),
              onTap: () async {
                if (state.isSolve == null) {
                  CommonUtils.showErrorInfo(viewService.context, '请选择报装结果');
                  return;
                }

                CommonUtils.showWaitLoading(viewService.context);
                Map info = {};
                if (state.model.itemType == '6') {
                  info['ConfigValue'] = state.textEditingController.text;
                  info['ConfigKey'] = state.isOther ? '其他情况' : state.content;
                  info['ConfigId'] = '1';
                } else {
                  List<String> items = [state.isOther ? '其他情况' : state.content];
                  if (state.textEditingController.text.isNotEmpty) {
                    items.add(state.textEditingController.text);
                  }
                  info['RepairContent'] = items.join(':');
                }
                List item = [info];
                ResultData res = await CommonNetWork.engineerOrderFix(
                  state.model.itemID,
                  status: 5,
                  content: state.model.itemType == '6'
                      ? jsonEncode(item)
                      : jsonEncode(info),
                  isSolve: state.isSolve,
                );
                Navigator.pop(viewService.context);
                if (res.success) {
                  bus.emit('refreshList');
                  await CommonUtils.showAlertView(viewService.context, '提交成功');
                  Navigator.popUntil(
                      viewService.context, ModalRoute.withName('/'));
                } else {
                  CommonUtils.showErrorInfo(viewService.context, res.desc);
                }
              },
            ),
          ),
        ],
      ),
      onTap: () => CommonUtils.closeKey(viewService.context),
    );
  }

  Widget _orderFireContent() {
    return MyInkWellWidget(
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.only(left: 15, right: 15, bottom: 15),
            decoration: BoxDecoration(
                color: Colors.white,
                border: Border(
                    bottom:
                    BorderSide(color: ThemeConfig.separeColor, width: 10))),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  height: 44,
                  child: Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      '隐患整改',
                      style: TextThemeConfig.Font16WithColorBold22,
                    ),
                  ),
                ),
                Container(
                  height: 100,
                  child: TextField(
                    minLines: 1,
                    maxLines: 10,
                    style: TextThemeConfig.Font13WithColor22,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: "情况说明...",
                      hintStyle: TextThemeConfig.Font13WithColor99,
                      contentPadding: EdgeInsets.only(bottom: 12),
                    ),
                    controller: state.textEditingController,
                  ),
                ),
              ],
            ),
          ),
          _orderPhotoWidget(),
          Container(
            margin: EdgeInsets.only(left: 15, right: 15, top: 30, bottom: 12),
            height: 45,
            decoration: BoxDecoration(
              color: ThemeConfig.mainColor,
              borderRadius: BorderRadius.all(Radius.circular(4)),
            ),
            child: InkWell(
              child: Center(
                child: Text(
                  '提交',
                  style: TextThemeConfig.Font16WithWhite,
                ),
              ),
              onTap: () async {
                CommonUtils.showWaitLoading(viewService.context);
                List<String> uploads = await CommonNetWork.multiUploadImgs(state.orderPhoto,
                    userNo: state.model.itemID);
                if (uploads == null) {
                  Navigator.pop(viewService.context);
                  CommonUtils.showErrorInfo(viewService.context, '上传图片失败，请重新上传');
                  return;
                }
                ResultData res = await CommonNetWork.engineerFireOrderContent(
                  itemId: state.model.itemID,
                  remark: state.textEditingController.text,
                  imageInfo: uploads.join(','),
                );

                Navigator.pop(viewService.context);
                if (res.success) {
                  bus.emit('refreshList');
                  await CommonUtils.showAlertView(viewService.context, '提交成功');
                  Navigator.popUntil(
                      viewService.context, ModalRoute.withName('/'));
                } else {
                  CommonUtils.showErrorInfo(viewService.context, res.desc);
                }
              },
            ),
          ),
        ],
      ),
      onTap: () => CommonUtils.closeKey(viewService.context),
    );
  }


  return Scaffold(
    appBar: myAppBar(viewService.context, title: '情况说明'),
    body:
        state.model.itemType == '2' ? _fixItemContent() : state.model.itemType == '6' ?_orderFireContent() : _engineerGasContent(),
  );
}
